#!/usr/bin/env ruby

require 'open-uri'
require 'uri'
require 'net/http'

$url  = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0'
$url += '&langpair='+($*.shift) +'%7C'+ ($*.shift)

def translate(text)
    url = $url+'&q='+URI.encode(text)
    
    json = Net::HTTP.get_response(URI.parse url).body
    # check for wrong response
    if json =~ /responseStatus"\s*:\s*200/
        print json.match('translatedText"\s*:\s*"(.*?)"\},')[1]
    else
        $stderr.puts "Could not translate \"#{text}\""
        $stderr.puts "    "+json.match(/responseDetails"\s*:\s*"(.*?)", /)[1]
        exit 1
    end
end

if $0 == __FILE__
    if $*.length > 0
        translate $*.join(' ')
    else
        ARGF.each{ |line|
            translate(line)
        }
    end
end
